# -*- coding: utf-8 -*-
import json
import time
import socket
import urllib.request as api_request
import urllib.error as api_error

from crawler.tools import get_nvd_key


class CVECrawler:

    def __init__(self, cve):
        self.cve = cve

    def crawl_cve_info(self):
        # 构建API请求
        api_key = get_nvd_key()
        url = f"https://services.nvd.nist.gov/rest/json/cves/2.0?cveId={self.cve}"
        print(url)

        # 调用API
        header = {'apiKey': api_key}
        r = api_request.Request(url, headers=header)
        try:
            response = api_request.urlopen(r, timeout=30)
            cve_info = json.load(response)
        except api_error.HTTPError as e:
            if e.code == 429:
                print(f"错误429: 爬取过快，尝试重新爬取CVE {self.cve}")
                time.sleep(10)
                return self.crawl_cve_info()
            else:  # CVE不存在
                print(f"错误{e.code}: 无法通过API请求获取CVE {self.cve}")
                return None
        except socket.error:  # 网速问题
            print(f"出错啦! 尝试重新爬取CVE {self.cve}")
            time.sleep(10)
            return self.crawl_cve_info()

        # 处理返回数据
        return cve_info
